package lab03.Test06;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
    StringBuffer sb=new StringBuffer();
        RandomAccessFile raf = new RandomAccessFile(new File("D:\\word.txt"), "r");
      String str=null;
        try {
            while((str=raf.readLine())!=null){
                sb.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String content=sb.toString();
        String[] wordArray=content.split("[^a-zA-Z]");
        Map<String,Integer> map=new HashMap<String,Integer>();
        for(String word:wordArray){
            if(!word.equals("")){
                if(map.containsKey(word)){
                    map.put(word,Integer.parseInt(map.get(word).toString())+1);}
                    else{
                        map.put(word,1);
                    }
                }
        }
            System.out.println("单词数量："+map.size());
            Set set = map.entrySet();
            List<Map.Entry<String,Integer>> list=new ArrayList<>();
            for(Iterator i=set.iterator();i.hasNext(););
        {
Map.Entry<String,Integer> entry=(Map.Entry<String,Integer>)i.next();
        if(entry.getValue().toString().equals("1")){
            System.out.println(entry.getKey()+":出现一次");
        }
        list.add(entry);
    }
    Collections.sort(list,new WordComparator());
    for(Map.Entry<String,Integer>entry:list)
    {
        System.out.println(entry.getKey()+":"+entry.getValue());
    }
}
    }
class WordComparator implements Comparator{
    public int compare(Object arg0,Object arg1)
    {
        Map.Entry<String,Integer>map1=(Map.Entry<String,Integer>)arg0;
        Map.Entry<String,Integer>map2=(Map.Entry<String,Integer>)arg1;
        return Integer.parseInt(map2.getValue().toString())-Integer.parseInt(map1.getValue().toString());
    }
}
